package com.bw.common.mvvm;

import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class BaseRespository {

    protected RequestBody createBody(Map<String,Object>map){
        return RequestBody.create(MediaType.parse("application/json"),new Gson().toJson(map));
    }
    protected Observable<BaseEntity> functionObservable(Observable observable){
        return observable.map(new RxFunction());
    }
    //合并请求
    protected Observable<BaseEntity>mergeObservable(Observable... observables){
        Observable<BaseEntity> observable = null;
        ArrayList<Observable<BaseEntity>> list = new ArrayList<>();
        //遍历可变参数->生成集合
        for (int i = 0;i < observables.length;i ++){
            list.add(functionObservable(observables[i]));
        }
        //使用合并操作符->将多个被观察任务合并为一个被观察者任务
        observable = Observable.merge(list);
        return observable;
    }

    protected Observable<BaseEntity> checkNetWork(Observable observable){
        Observable<BaseEntity> ob = null;
        //校验网络请求->无网络连接时->返回NetErroEntity任务
        if (NetworkUtils.isConnected()){
            ob = functionObservable(observable);
        }else {
            NetErroEntity entity = new NetErroEntity();
//            entity.status = NetFieldConst.NETERRO;
//            entity.message = NetFieldConst.NETERROMSG;
            Observable<NetErroEntity>netErroEntityObservable = Observable.just(entity);
            ob = functionObservable(netErroEntityObservable);
        }
        return ob;
    }



}
